package com.dtz.rabbitmq.ttl;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import com.dtz.rabbitmq.constant.ArgsConstant;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.AMQP.BasicProperties;

import lombok.extern.slf4j.Slf4j;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * 设置消息过期时间
 * 队列过期时间和消息过期时间同时设置时，过期时间短的为准
 * @param args
 */
@Slf4j
public class TtlMessage {

	public static void main(String[] args) {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setVirtualHost("/");
		factory.setHost("1.15.137.13");
		factory.setPort(5672);
		factory.setUsername("admin");
		factory.setPassword("admin");
		
		Connection connection = null;
		Channel channel = null;
		
		try {
			
			connection = factory.newConnection();
			
			channel = connection.createChannel();
			
			channel.queueDeclare("ttl.message.queue", true, false, false, null);
			
			BasicProperties properties = new AMQP.BasicProperties().builder()
				.deliveryMode(2)	
				.contentEncoding("UTF-8")
				.expiration("5000")
				.build();
			
			for (int i = 0; i < 10; i++) {
				String message = i + "";
				channel.basicPublish("", "ttl.message.queue", properties, message.getBytes());
			}
			
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		} finally {
			try {
				if (channel != null && channel.isOpen()) {
					channel.close();
				}
			} catch (IOException | TimeoutException e) {
				log.error(e.getMessage(), e);
			}
			try {
				if (connection != null && connection.isOpen()) {
					connection.close();
				}
			} catch (Exception e2) {
				log.error(e2.getMessage(), e2);
			}
		}
	}
	
}
